//
//  TemplateManageViewController.m
//  YuTang
//
//  Created by 葛悦彣 on 2024/7/16.
//

#import "TemplateManageViewController.h"
#import "TemplateManageModel.h"
#import "TemplateManageTableCell.h"
#import "TemplateFoundViewController.h"

#import "TemplateFoundDetailsViewController.h"
#import "TemplateFoundDetailsModel.h"
#import "TemplateScreenViewController.h"
#import "TemplateFoundXGViewController.h"

@interface TemplateManageViewController ()

@property (nonatomic ,strong) UIButton * GGBtn;
@property (nonatomic ,strong) UIButton * GRBtn;
@property (nonatomic ,strong) UIButton * SeledBtn;
@property (nonatomic ,strong) UIView * line;

@property (nonatomic ,strong) NSMutableArray <TemplateManageModel *>* modelArray;

///添加
@property (nonatomic ,strong) UIImageView * TJimg;
@property (nonatomic ,strong)  UIButton * SXBtn ;
///只放   模板id    池塘类型id,逗号分割
@property (nonatomic ,strong)  NSMutableDictionary * dict ;
@property (nonatomic ,strong)  NSMutableDictionary * GRdict ;
@property (nonatomic ,strong)  NSURLSessionDataTask * GRTask ;
@property (nonatomic ,strong)  NSURLSessionDataTask * GGTask ;

@end

@implementation TemplateManageViewController
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(self.SeledBtn){
        if(self.SeledBtn == self.GRBtn){
            NSString * ID = [self.GRdict objectForKey:@"id"];
            NSString * pondTypeId = [self.GRdict objectForKey:@"pondTypeId"];
            self.SXBtn.selected = (ID.length > 0 || pondTypeId.length > 0);
        }else {
            NSString * ID = [self.dict objectForKey:@"id"];
            NSString * pondTypeId = [self.dict objectForKey:@"pondTypeId"];
            self.SXBtn.selected = (ID.length > 0 || pondTypeId.length > 0);
        }
        [self refreshingData];
    }
}
- (NSMutableDictionary *)dict{
    if(!_dict){
        _dict = [NSMutableDictionary dictionaryWithDictionary:@{@"id":@"",
                                                                @"pondTypeId":@""}];
        
    }
    return _dict;
}
- (NSMutableDictionary *)GRdict{
    if(!_GRdict){
        _GRdict = [NSMutableDictionary dictionaryWithDictionary:@{@"id":@"",
                                                                @"pondTypeId":@""}];
        
    }
    return _GRdict;
}
- (NSMutableArray<TemplateManageModel *> *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
}
- (void)setupView{
    UIView * topview = [UIView new];
    topview.backgroundColor = KcolorHex(@"#0967FF");
    [self.view addSubview:topview];
    [topview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.offset(Knav_HeightX);
    }];
    MJWeakSelf
    UIView * backview = [UIView new].addClickBlock(^{
        [weakSelf popViewController];
    });
    [topview addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(44);
        make.left.bottom.offset(0);
        make.width.offset(kwt(140));
    }];
    
    UIImageView * leftimg = kimageView(@"white_path");
    [backview addSubview:leftimg];
    [leftimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(20);
        make.left.offset(kwt(10));
        make.centerY.offset(0);
    }];
    
    
    
    
    UILabel * leftlab = [DTKTool labelWithText:@"模版管理" andFont:kCFont(19) andTextColor:UIColor.whiteColor];
    [backview addSubview:leftlab];
    [leftlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(43));
        make.centerY.offset(0);
    }];

//    UIImageView * rightimg = kimageView(@"seach");
//    rightimg.addClickBlock(^{
//        [weakSelf openSS];
//    });
//    [topview addSubview:rightimg];
//    [rightimg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.height.offset(29);
//        make.right.offset(kwt(-15));
//        make.centerY.equalTo(backview);
//    }];
    
    UIImageView * TJimg = kimageView(@"chuangjian");
    self.TJimg = TJimg;
    TJimg.addClickBlock(^{
        TemplateFoundViewController * vc = [TemplateFoundViewController new];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    });
    [topview addSubview:TJimg];
    [TJimg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(29);
        make.right.offset(kwt(-15));
        make.centerY.equalTo(backview);
    }];
    
    UIView * btnview = [UIView new];
    btnview.backgroundColor = KcolorHex(@"#F1F5FA");
    [self.view addSubview:btnview];
    [btnview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(topview.mas_bottom);
        make.height.offset(kwt(48));
    }];
    
    UIButton * GGBtn = [UIButton buttonWithType:0];
    GGBtn.addNormalText(@"公共模版").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(17)).addTarget(self,@selector(GGbtnClick));
    self.GGBtn = GGBtn;
    [btnview addSubview:GGBtn];
    [GGBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.offset(0);
        make.width.offset(kwt(90));
    }];
    
    UIButton * GRBtn = [UIButton buttonWithType:0];
    GRBtn.addNormalText(@"个人模版").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(17)).addTarget(self,@selector(GRbtnClick));
    self.GRBtn = GRBtn;
    [btnview addSubview:GRBtn];
    [GRBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.offset(0);
        make.width.offset(kwt(90));
        make.left.equalTo(GGBtn.mas_right);
    }];
    
    UIButton * SXBtn = [UIButton buttonWithType:0];
    self.SXBtn = SXBtn;
    SXBtn.addTarget(self,@selector(SXBtnClick));
    SXBtn.addNormalText(@"筛选").addNormalColor(KcolorHex(@"#222222")).addFont(kFont(17));
    [SXBtn setTitleColor:KcolorHex(@"#0967FF") forState:UIControlStateSelected];
    [SXBtn setImage:[UIImage imageNamed:@"CRscreen"] forState:UIControlStateNormal];
    [SXBtn setImage:[UIImage imageNamed:@"CRscreen2"] forState:UIControlStateSelected];
    [SXBtn setImageEdgeInsets:UIEdgeInsetsMake(0, kwt(50), 0, 0)];
    [SXBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, kwt(-40), 0, 0)];
    [btnview addSubview:SXBtn];
    [SXBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.top.offset(0);
        make.width.offset(kwt(80));
    }];
    
    UIView * line = [UIView new];
    self.line = line;
    line.backgroundColor = KcolorHex(@"#1983FA");
    line.frame = CGRectMake(kwt(33), kwt(45), kwt(26), kwt(3));
    [btnview addSubview:line];
    [DTKTool YJ:kwt(1.5) andView:line];
    
    
    [self.view addSubview:self.tableview];
    self.tableview.backgroundColor = KcolorHex(@"#ECEDEE");
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(btnview.mas_bottom);
    }];
    [self addFooterView:^{
        [weakSelf addMoreData];
    }];
    [self addHeaderView:^{
        [weakSelf refreshingData];
    }];
    [self GGbtnClick];
    
}

- (void)SXBtnClick{
    TemplateScreenViewController * vc = [TemplateScreenViewController new];
    vc.isGR = (self.SeledBtn == self.GRBtn);
    vc.dict = (self.SeledBtn == self.GRBtn)?self.GRdict:self.dict;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)refreshingData{
    self.pageNo = 1;
    [self.modelArray removeAllObjects];
    [self loadNewData];
}

-(void)addMoreData{
    self.pageNo += 1;
    [self loadNewData];
}

- (void)GGbtnClick{
    if(self.SeledBtn != self.GGBtn){
        self.GGBtn.addFont(kCFont(19));
        self.GRBtn.addFont(kFont(17));
        self.SeledBtn = self.GGBtn;
        self.TJimg.hidden = YES;
        if(self.SeledBtn.mj_w){///避免第一次进入为0
            [UIView animateWithDuration:0.25 animations:^{
                self.line.mj_x = self.SeledBtn.mj_x + self.SeledBtn.mj_w/2-kwt(13);
            }];
        }
        [self refreshingData];
        
        NSString * ID = [self.dict objectForKey:@"id"];
        NSString * pondTypeId = [self.dict objectForKey:@"pondTypeId"];
        self.SXBtn.selected = (ID.length > 0 || pondTypeId.length > 0);
        
    }
    
}
- (void)GRbtnClick{
    if(self.SeledBtn != self.GRBtn){
        self.GRBtn.addFont(kCFont(19));
        self.GGBtn.addFont(kFont(17));
        self.SeledBtn = self.GRBtn;
        self.TJimg.hidden = NO;
        [UIView animateWithDuration:0.25 animations:^{
            self.line.mj_x = self.SeledBtn.mj_x+self.SeledBtn.mj_w/2-kwt(13);
        }];
        [self refreshingData];
        NSString * ID = [self.GRdict objectForKey:@"id"];
        NSString * pondTypeId = [self.GRdict objectForKey:@"pondTypeId"];
        self.SXBtn.selected = (ID.length > 0 || pondTypeId.length > 0);
        
    }
    
}

- (void)loadNewData{
    if(self.SeledBtn == self.GGBtn){
        [self GGApi];
    } else {
        [self GRApi];

    }
}

- (void)GGApi{
    if(self.GGTask){
        [self.view hideBusyHUD];
        [self.GGTask cancel];
    }
    [self.view showBusyHUD];
   
    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:self.dict];
    NSMutableArray<NSString *>* pondTypearray = [[[dic objectForKey:@"pondTypeId"] componentsSeparatedByString:@","] mutableCopy];
    if([pondTypearray containsObject:@"****"]){///移除全部
        [pondTypearray removeObject:@"****"];
    }
    [dic setObject:[pondTypearray componentsJoinedByString:@","] forKey:@"pondTypeId"];

    [dic setObject:@(self.pageNo) forKey:@"pageNo"];
    [dic setObject:@(self.pageSize) forKey:@"pageSize"];
    self.GGTask = [SCNetManger PostCommonListWithDict:dic andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        NSLog(@"%@",model);
        if(model.code ==200){
            [self.tableview.mj_footer endRefreshing];
            [self.tableview.mj_header endRefreshing];
            NSArray * array = [NSArray yy_modelArrayWithClass:TemplateManageModel.class json:[model.result objectForKey:@"records"]];
            [self.modelArray addObjectsFromArray:array];
            if(array.count == 0 && self.modelArray.count > 0){
                [self.tableview.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableview.mj_footer resetNoMoreData];
            }
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}


- (void)GRApi{
    if(self.GRTask){
        [self.view hideBusyHUD];
        [self.GRTask cancel];
    }
    [self.view showBusyHUD];
    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:self.GRdict];
    NSMutableArray<NSString *>* pondTypearray = [[[dic objectForKey:@"pondTypeId"] componentsSeparatedByString:@","] mutableCopy];
    if([pondTypearray containsObject:@"****"]){///移除全部
        [pondTypearray removeObject:@"****"];
    }
    [dic setObject:[pondTypearray componentsJoinedByString:@","] forKey:@"pondTypeId"];
    [dic setObject:@(self.pageNo) forKey:@"pageNo"];
    [dic setObject:@(self.pageSize) forKey:@"pageSize"];

    self.GRTask = [SCNetManger PostPersonalListWithDict:dic andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        NSLog(@"%@",model);
        if(model.code ==200){
            [self.tableview.mj_footer endRefreshing];
            [self.tableview.mj_header endRefreshing];
            NSArray * array = [NSArray yy_modelArrayWithClass:TemplateManageModel.class json:[model.result objectForKey:@"records"]];
            [self.modelArray addObjectsFromArray:array];
            if(array.count == 0 && self.modelArray.count > 0){
                [self.tableview.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableview.mj_footer resetNoMoreData];
            }
            [self.tableview reloadData];
        } else {
            [self.view showWarning:model.message];
        }
    }];
}
///搜索
- (void)openSS{
}
///筛选
- (void)openSX{
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * view = [UIView new];
    UIView * wbview = [UIView new];
    view.clipsToBounds = YES;
    wbview.backgroundColor = KcolorHex(@"#FFDBDA");
    [view addSubview:wbview];
    [wbview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(kwt(38));
        make.bottom.offset(kwt(-5));
    }];
    
    UILabel * lab = [DTKTool labelWithText:@"点击”创建模版”可创建该公共模板的个人模版" andFont:kFont(16) andTextColor:KcolorHex(@"#FE0202")];
    [wbview addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kwt(12));
        make.centerY.offset(0);
    }];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return (self.SeledBtn == self.GGBtn)? kwt(43) : kwt(5);
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return self.modelArray[indexPath.row].CellH;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    TemplateManageTableCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TemplateManageTableCell"];
    if (cell == nil) {
        cell = [[TemplateManageTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TemplateManageTableCell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.modelArray[indexPath.row];
    [cell setIndex:indexPath.row + 1 andIsGG:(self.SeledBtn == self.GGBtn)];
    MJWeakSelf
    cell.openGGBlock = ^(TemplateManageModel * _Nonnull model) {
        TemplateFoundViewController *  vc = [TemplateFoundViewController new];
        vc.model = model;
        vc.overBlock = ^{
            [weakSelf GRbtnClick];
        };
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.openGRBlock = ^(TemplateManageModel * _Nonnull model) {
        [weakSelf GRMBXGwithModel:model];
    };
    
    return cell;
}
- (void)GRMBXGwithModel:(TemplateManageModel *)model{
    [self.view showBusyHUD];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setObject:model.ID forKey:@"id"];
    ///个人模版
    [SCNetManger PostGRMBDetailWithDict:dict andCompetionHandlerBlock:^(HTTPDicBase * model) {
        [self.view hideBusyHUD];
        if(model.code == 200){
            MJWeakSelf
            TemplateFoundDetailsModel * m = [TemplateFoundDetailsModel yy_modelWithJSON:model.result];
            TemplateFoundXGViewController * vc = [TemplateFoundXGViewController new];
            vc.model = m;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            [self.view showWarning:model.message];
        }
    }];
    
}

@end
